#include "place_sub_category_view.h"
#include "ui_place_sub_category_view.h"

#include "place_list_view.h"

PlaceSubCategoryView::PlaceSubCategoryView(QWidget *parent) :
    ViewBase(parent),
    ui(new Ui::PlaceSubCategoryView),
    placeListView_(0)
{
    ui->setupUi(this);

    QAction *backSoftkeyAction = new QAction(QString("Back"), this);
    backSoftkeyAction->setSoftKeyRole(QAction::NegativeSoftKey);
    QObject::connect(backSoftkeyAction, SIGNAL(triggered()),
                     this, SLOT(hide()));
    addAction(backSoftkeyAction);

    connect(ui->lstPlaceSubCategories, SIGNAL(itemActivated(QListWidgetItem *)),
            this, SLOT(showPlaceList(QListWidgetItem*)));
}

PlaceSubCategoryView::~PlaceSubCategoryView()
{
    delete ui;
    if (placeListView_) {
        delete placeListView_;
    }
}


void PlaceSubCategoryView::IssueRequest() {
  RequestMethod request(this, QString("xml"), QString("Places.getSubcate"));
  request.AddParam(QString("category"), cate_.cn_cate);

  placeSubCategories_.clear();

  ui->lstPlaceSubCategories->clear();

  if (handler_) {
    handler_->IssueRequest(request);
  }
}

int PlaceSubCategoryView::ProcessResult(RequestMethod &, QDomElement &e) {
  int re = parse_result(e);
  if (re == 0) {
    for (int i = 0; i < placeSubCategories_.count(); ++i) {
      cate &c = placeSubCategories_[i];
      ui->lstPlaceSubCategories->addItem(c.cn_cate);
    }
  }
  return re;
}

int PlaceSubCategoryView::parse_result(QDomElement &e) {
  QDomNodeList list = e.childNodes();
  for (int i = 0; i < list.count(); ++i) {
    QDomElement n = list.at(i).toElement();
    if (n.nodeName() == QString("cate")) {
      cate c;
      parse_cate(n, c);
      placeSubCategories_.push_back(c);
    }
  }

  return 0;
}

void PlaceSubCategoryView::showPlaceList(QListWidgetItem *item) {
    for (int i = 0; i < placeSubCategories_.count(); ++i) {
        cate &c = placeSubCategories_[i];
        if (c.cn_cate == item->text()) {
            if (!placeListView_) {
                placeListView_ = new PlaceListView(this);
                placeListView_->SetRequestHandler(handler_);
            }
            placeListView_->SetCategoryAndSubCate(cate_, c);

            placeListView_->Show();
            placeListView_->IssueRequest();

            return;
        }
    }
}
